package C8_3_ChangeValueToReference;

import C8_2_ReplaceDataValueWithObject.C8_2_demo;

import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;

/**
 * Desc:&emsp;&ensp;将值对象改为引用对象，将相等的值对象替换为同一个对象
 *
 * 在一个值对象中保存少量不可修改的数据，之后有需要添加一些可修改的数据
 * @author 李渊&emsp;
 * @version 1.0
 * @since V4.3&emsp;2022/7/13
 */
public class C8_3_demo {

    //==========重构前===========
    // 订单类
    class Order_1{
        // 客户
        private String _cus;

        public Order_1(String _cus) {
            this._cus = _cus;
        }

        public String get_cus() {
            return _cus;
        }

        public void set_cus(String _cus) {
            this._cus = _cus;
        }
    }
    // 使用order类的方法
    public static final int numberOfOrderFor(Collection<Order_1> orders, String cus) {
        return  (int) orders.stream().filter(order -> order.get_cus().equals(cus)).count();
    }

    //==========重构后===========
    // 使用工厂函数进行构造
    static class Cus{
        private final String name;

        public static final Cus create(String name){
            return new Cus(name);
        }

        public static final Cus getNamed(String name){
            return (Cus)_instances.get(name);
        }

        private Cus(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        // 如何访问cus

        private static Dictionary _instances = new Hashtable();
        private void store(){
            _instances.put(this.getName(), this);
        }
        // 初始化一些cus
        static void loadCuss(){
            new Cus("A").store();
            new Cus("B").store();
            new Cus("C").store();
        }
    }

    // 订单类
    class Order_2{
        // 客户
        private Cus _cus;

        public Order_2(String cusName) {
            this._cus = Cus.getNamed(cusName);
        }

        public String get_cus() {
            return _cus.getName();
        }

        public void set_cus(String cusName) {
            this._cus = Cus.getNamed(cusName);
        }
    }
}
